<template>
  <div class="app-container">
    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="handleAdd"
      style="margin-bottom: 10px"
      >添加计划
    </el-button>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="projectId">
        <el-select v-model="form.projectId" placeholder="请选择项目">
          <el-option-group
            v-for="dict in dict.type.ly_group"
            :key="dict.value"
            :label="dict.label"
          >
            <el-option
              v-for="item in getProjectOption(
                groupAndProjectOptions,
                dict.value
              )"
              :key="item.projectId"
              :label="item.projectName"
              :value="item.projectId"
            >
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item prop="examinePlanTitle">
        <el-input
          v-model="queryParams.examinePlanTitle"
          placeholder="计划名称"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="planList"
      @selection-change="handleSelectionChange"
      :border="true"
    >
      <el-table-column
        label="计划名称"
        align="center"
        prop="examinePlanTitle"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="所属企业" align="center" prop="groupId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ly_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column
        label="所属项目"
        align="center"
        prop="projectName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="类型" align="center" prop="examineCateType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ly_inspection_type"
            :value="scope.row.examineCateType"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="examinePlanStatus">
        <template slot-scope="scope">
          <span
            :class="{
              ing: scope.row.examinePlanStatus === '1',
              start: scope.row.examinePlanStatus === '0',
            }"
          >
            {{
              scope.row.examinePlanStatus === "0"
                ? "待启动"
                : scope.row.examinePlanStatus === "1"
                ? "执行中"
                : scope.row.examinePlanStatus === "2"
                ? "已完成"
                : null
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="examinePlanSort" />
      <el-table-column
        label="年份季度"
        align="center"
        prop="examinePeriod"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="计划起始日期"
        align="center"
        prop="startTime"
        :show-overflow-tooltip="true"
        width="120px"
      />
      <el-table-column
        label="计划结束日期"
        align="center"
        prop="endTime"
        :show-overflow-tooltip="true"
        width="120px"
      />
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="300px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateOrDetail(scope.row)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateOrDetail(scope.row)"
            :disabled="scope.row.examinePlanStatus === '0'"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="changeTheCheckpointPerson(scope.row)"
            >更改巡点人</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            disabled
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改巡检计划对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :fullscreen="true"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :show-message="false"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业·项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择">
                <el-option-group
                  v-for="dict in dict.type.ly_group"
                  :key="dict.value"
                  :label="dict.label"
                >
                  <el-option
                    v-for="item in getProjectOption(
                      groupAndProjectOptions,
                      dict.value
                    )"
                    :key="item.projectId"
                    :label="item.projectName"
                    :value="item.projectId"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="examinePlanTitle">
              <el-input v-model="form.examinePlanTitle"> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="巡检类型" prop="examineProjectType">
              <el-select
                v-model="form.examineProjectType"
                placeholder="请选择"
                @change="examineProjectTypeChange"
              >
                <el-option
                  v-for="dict in dict.type.ly_inspection_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="寻点人" prop="examine_allow_user_ids">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <el-input :readonly="true" :value="'666'" />
                <el-button
                  type="text"
                  style="font-weight: bold; margin-left: 10px"
                >
                  查询
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="选择巡检区域"
          v-show="form.examineProjectType"
          prop="inspectionArea"
        >
          <div
            style="
              border: 1px solid #e6e6e6;
              width: 50%;
              max-height: 300px;
              overflow: auto;
            "
          >
            <el-tree
              :data="inspectionAreaData"
              show-checkbox
              node-key="id"
              ref="inspectionAreaTree"
              :props="inspectionAreaProps"
            >
            </el-tree>
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="年份" prop="examineYear">
              <el-date-picker
                v-model="form.examineYear"
                type="year"
                format="yyyy"
                value-format="yyyy"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="季度" prop="examineQuarter">
              <el-select v-model="form.examineQuarter">
                <el-option key="01" label="第一季度" value="01"></el-option>
                <el-option key="02" label="第二季度" value="02"></el-option>
                <el-option key="03" label="第三季度" value="03"></el-option>
                <el-option key="04" label="第四季度" value="04"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="排序" prop="examinePlanSort">
              <el-input v-model="form.examinePlanSort" style="width: 223px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="计划起始日期" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计划结束日期" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="examinePlanStatus">
              <el-select v-model="form.examinePlanStatus">
                <el-option key="0" label="待启动" value="0"></el-option>
                <el-option key="1" label="执行中" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="计划简介" prop="examinePlanRemark">
          <el-input
            v-model="form.examinePlanRemark"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlan,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  getAreaByTypeApi,
} from "@/api/inspection/plan";
import { getAllGroupAndProjectApi } from "@/api/inspection/config";

export default {
  name: "Plan",
  dicts: ["ly_inspection_type", "ly_group"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检计划表格数据
      planList: [],
      // 企业项目数据列表
      groupAndProjectOptions: [],
      // 巡检区域数据
      inspectionAreaData: [],
      // 巡检区域树结构配置
      inspectionAreaProps: {
        children: "children",
        label: "name",
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        examinePlanTitle: null,
        groupId: null,
        projectId: null,
      },
      // 年份
      examineYear: null,
      // 季度
      examineQuarter: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        examinePlanTitle: [
          { required: true, message: "不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "项目id不能为空", trigger: "change" },
        ],
        examineCateType: [
          { required: true, message: "1区域2楼栋不能为空", trigger: "change" },
        ],
        examineProjectType: [
          { required: true, message: "巡检类型不能为空", trigger: "change" },
        ],
        // examine_allow_user_ids: [
        //   { required: true, message: "不能为空", trigger: "blur" },
        // ],

        examineYear: [
          {
            required: true,
            trigger: "change",
          },
        ],
        examineQuarter: [
          {
            required: true,
            message: "不能为空",
            trigger: "change",
          },
        ],
        startTime: [
          { required: true, message: "计划起始日期不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "计划结束日期不能为空", trigger: "blur" },
        ],
        examinePlanStatus: [
          {
            required: true,
            message: "巡检计划状态0待启动1执行中2已完成不能为空",
            trigger: "change",
          },
        ],
        examinePlanSort: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getAllGroupAndProject();
  },
  methods: {
    /** 查询巡检计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then((response) => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询企业·项目列表 */
    getAllGroupAndProject() {
      getAllGroupAndProjectApi().then((response) => {
        this.groupAndProjectOptions = response.data;
      });
    },
    getProjectOption(groupAndProjectOptions, groupId) {
      const data = groupAndProjectOptions.filter(
        (option) => option.groupId === groupId
      );
      return data.length ? data[0].projectList : [];
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examinePlanId: null,
        examinePlanTitle: null,
        groupId: null,
        projectId: null,
        examineCateType: null,
        examineProjectType: null,
        examinePeriod: null,
        examineAllowUserIds: [],
        chooseSiteGroups: [],
        chooseBans: [],
        chooseMeets: [],
        startTime: null,
        endTime: null,
        examinePlanRemark: null,
        examinePlanStatus: null,
        examinePlanSort: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.examinePlanId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检计划";
    },
    /** 修改详情按钮操作 */
    handleUpdateOrDetail(row) {
      this.reset();
      const examinePlanId = row.examinePlanId || this.ids;
      getPlan(examinePlanId).then((response) => {
        this.form = response.data;
        this.form.examineYear = this.form.examinePeriod.substring(0, 4);
        this.form.examineQuarter = this.form.examinePeriod.substring(4);
        // 获取巡检区域数据
        this.examineProjectTypeChange(this.form.examineProjectType);
        this.$nextTick(() => {
          this.$refs.inspectionAreaTree.setCheckedKeys([
            ...JSON.parse(this.form.chooseSiteGroups),
            ...JSON.parse(this.form.chooseBans),
            ...JSON.parse(this.form.chooseMeets),
          ]);
        });
        this.open = true;
        this.title = "修改巡检计划";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examinePlanIds = row.examinePlanId || this.ids;
      this.$modal
        .confirm('是否确认删除巡检计划编号为"' + examinePlanIds + '"的数据项？')
        .then(function () {
          return delPlan(examinePlanIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 更改巡点人 */
    changeTheCheckpointPerson(row) {},
    /** 巡检区域转换 */
    formatInspectionAreaData() {
      const selectedAreaNodeList =
        this.$refs.inspectionAreaTree.getCheckedNodes(true);
      const workSpaceList = [];
      const meetingList = [];
      const banList = [];
      // 选择区域
      if (this.form.examineProjectType === "1") {
        selectedAreaNodeList.forEach((item) => {
          if (item.type === 1) {
            // 工作区
            workSpaceList.push(item.id);
          } else if (item.type === 2) {
            // 会议室
            meetingList.push(item.id);
          }
        });
      }
      // 选择楼栋
      else {
        selectedAreaNodeList.forEach((item) => {
          if (item.type === 3) {
            // 楼栋
            banList.push(item.id);
          }
        });
      }
      return { workSpaceList, meetingList, banList };
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log(valid);
        if (valid) {
          const data = this.formatInspectionAreaData();
          this.form.chooseSiteGroups = JSON.stringify(data.workSpaceList);
          this.form.chooseMeets = JSON.stringify(data.meetingList);
          this.form.chooseBans = JSON.stringify(data.banList);
          // 转换季度
          this.form.examinePeriod =
            this.form.examineYear + this.form.examineQuarter;
          // 寻点人
          this.form.examineAllowUserIds = "666";
          if (this.form.examinePlanId != null) {
            updatePlan(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 巡检类型变化
    examineProjectTypeChange(value) {
      getAreaByTypeApi(value).then((res) => {
        this.inspectionAreaData = res.data;
      });
    },
  },
};
</script>

<style scoped lang="scss">
.ing {
  color: darkblue;
}
.start {
  color: green;
}
</style>
